package com.charge.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Description : Session超时拦截器
 * Author : buf
 * Date : 2018/8/10 10:55
 **/
public class SessionTimeoutInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        String redirectUrl = request.getRequestURI();
        HttpSession session = request.getSession(true);
        // session中获取用户名信息
        Object user = session.getAttribute("user");
        if (user == null || "".equals(user.toString())) {
            //如果判断是 AJAX 请求,直接设置为session超时
            if( request.getHeader("x-requested-with") != null
                    && request.getHeader("x-requested-with").equals("XMLHttpRequest")  ) {

                response.setHeader("sessionstatus", "timeout");
                response.sendError(518, "session timeout.");

            } else{
                response.sendRedirect(
                        request.getSession().getServletContext().getContextPath()
                                + "/login?redirectUrl=" + redirectUrl);
            }
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
